<?php

function isLogged($loginPage) {
      if ( $_SESSION['loggedInTheSystem'] == true ) {
            return true;
      }
      elseif ( !$loginPage ) {
            header('Location: index.php?do=login');
            exit;
      }
      else {
            return false;
      }
}

/**
 * Test for correct login data
 * @param string $username The Username, restricted to /[^a-zA-Z0-9-.]/i
 * @param string $password The Password
 * @param resource $link DB connection link
 * @return bool 
 */
function checkLogin($username, $password, $link) {
      $sql = 'SELECT * FROM users WHERE username = "' . mysqli_real_escape_string($link, $username) . '" and password = "' . mysqli_real_escape_string($link, $password) . '"';
      $result = mysqli_query($link, $sql);

      if ( $result->num_rows == 1 ) {
            $userInfo = $result->fetch_assoc();
            $_SESSION['user_id'] = $userInfo['id'];
            $_SESSION['username'] = $userInfo['username'];
            return true;
      }
      else {
            //Грешни данни
            return false;
      }
}

/**
 * Регистрация на нов потребител. Ако всичко е успешно записва в $_SESSION['logged'] = true; И пренасочва към messages.php
 * @param string $username The Username, restricted to /[^a-zA-Z0-9-.]/i
 * @param string $password The Password
 * @param resource $link DB connection link
 * @return mixed On succes Login and redirect to messages.php.<br>On error return false  
 */
function registerNewUser($username, $password, $link) {
      $sql = 'INSERT INTO users (username, password) VALUES ("' . mysqli_real_escape_string($link, $username) . '", "' . mysqli_real_escape_string($link, $password) . '")';
      $result = mysqli_query($link, $sql);

      if ( $result ) {
            $_SESSION['loggedInTheSystem'] = true;
            $_SESSION['user_id'] = $userInfo['id'];
            $_SESSION['username'] = $userInfo['username'];
            header('Location: messages.php?message=11');
            exit;
            return true;
      }
      else {
            return false;
      }
}

/**
 * Check if username is exists
 * @param string $username The Username, restricted to /[^a-zA-Z0-9-.]/i
 * @param resource $link DB connection link
 * @return bool 
 */
function usernameExists($username, $link) {
      $sql = 'SELECT * FROM users WHERE username = "' . mysqli_real_escape_string($link, $username) . '"';
      $result = mysqli_query($link, $sql);

      if ( $result->num_rows == 1 ) {
            return true;
      }
      else {
            //Грешни данни
            return false;
      }
}

/** Adding new message
 * @param string $title The thext of message
 * @param string $text The thext of message
 * @param int $user_id The who added message
 * @param resource $link DB connection link
 * @return mixed On success return message id, else false
 */
function addMessage($title, $text, $user_id, $link) {
      $sql = 'INSERT INTO 	messages (date, title, text, user_id) VALUES (
             "' . date('Y-m-d H:i:s') . '", 
             "' . mysqli_real_escape_string($link, $title) . '", 
             "' . mysqli_real_escape_string($link, $text) . '", 
             "' . (int) $user_id . '")';
      $result = mysqli_query($link, $sql);

      if ( $result ) {
            return mysqli_insert_id($link);
      }
      else {
            return false;
      }
}

/**
 * If user can delete message
 * @param int $user_id The who added message
 * @param int $messageId Message ID
 * @param resource $link DB connection link
 * @return bool
 */
function canDeleteMessage($userId, $messageId, $link) {
      $sql = 'SELECT * FROM messages WHERE id = "' . (int) $messageId . '" and user_id = "' . (int) $userId . '" ';
      $result = mysqli_query($link, $sql);

      if ( $result->num_rows == 1 ) {
            return true;
      }
      else {
            return false;
      }
}


function deleteMessage($messageId, $link) {
      
}
/**
 * Return ready to show html table
 * @param array $filters
 * @param resource $link
 * @return string|boolean 
 */
function showAllMessages($filters, $link) {
      //Няма да покаже съобщения на потребители, които несъществуват
      $sql = 'SELECT messages.id, messages.date, messages.title, messages.text, messages.user_id, users.username  FROM messages 
                  LEFT JOIN users
                  ON messages.user_id = users.id
                  ORDER BY messages.date DESC';

      $result = mysqli_query($link, $sql);

      if ( $result->num_rows > 0 ) {
            $return = '<table class="list wf">
                  <tr>
                  <th>№</th>
                  <th>Дата</th>
                  <th>Съобщение</th>
                  <th>От потребител</th>
                  
                  </tr>';#<th>Действие</th>

            while ($row = $result->fetch_assoc()) {
                  $i++;
                  if ( $i % 2 ) {
                        $trClass = 'even';
                  }
                  else {
                        $trClass = 'odd';
                  }
                  if ($_GET[mid] == $row[id]) {
                        $highlighted = ' future';
                  }
                  else {
                        $highlighted = '';
                  }
                  
                  if ( substr_count($row[text], "\n") < 4) {
                        $row[text] = str_replace("\n", '<br />', $row[text]);
                  }
                  $return .= '<tr class="' . $trClass . $highlighted . '">
                        <td>' . $i . '</td>
                        <td>' . $row[date] . '</td>
                        <td><strong>' . $row[title] . '</strong><br>' . $row[text] . '</td>
                        <td>' . $row[username] . '</td>
                        
                        </tr>';#<td>' . $row[id] . '</td>
            }
            $return .= '</table>';


            return $return;
      }
      else {
            return false;
      }
}

/**
 * Different welcome message based on the time of the day
 * @return string The message
 */
function welcomeMessage() {
      $today = date('h');
      //Кирий да допиша : )

      if ( $_SESSION['username'] ) {
            return 'Здравей, ' . $_SESSION['username'];
      }
}

function getMsgFilters() {
      global $messageErrors;
      /* Филтриране по потребител */
      if ( !empty($_GET['filterUser']) ) {
            $filters['filterUser'] = (int)$_GET['filterUser'];
      }
      
      /* Подредба по дата */
      if ( !empty($_GET['filterDateOrder']) ) {
            $filters['filterDateOrder'] = (int)$_GET['filterDateOrder'];
      }
      
      /* Филтриране по начална дата на качване */
      if ( !empty($_GET['filterByStartDate']) ) {
            $startDate = preg_replace('/[^0-9-]/', '', $_GET['filterByStartDate']);
            $startDateFormatError = false;
            if ( strlen($startDate) != 10 ) {
                  $startDateFormatError = true;
            }
            else {
                  $dateExpl = explode('-', $startDate);
                  if ( count($dateExpl) != 3 ) {
                        $startDateFormatError = true;
                  }
                  elseif ( !checkdate((int) $dateExpl[1], (int) $dateExpl[0], (int) $dateExpl[2]) ) {
                        $startDateFormatError = true;
                  }
            }
            if ( $startDateFormatError ) {
                  $messageErrors[] = 16;
                  unset($startDate);
            }
            else {
                  $filters['startDate'] = strtotime("$startDate 00:00:00");
            }
      }

      /* Филтриране по крайна дата на качване */
      if ( !empty($_GET['filterByEndDate']) ) {
            $endDate = preg_replace('/[^0-9-]/', '', $_GET['filterByEndDate']);
            $endDateFormatError = false;
            if ( strlen($endDate) != 10 ) {
                  $endDateFormatError = true;
            }
            else {
                  $dateExpl = explode('-', $endDate);
                  if ( count($dateExpl) != 3 ) {
                        $endDateFormatError = true;
                  }
                  elseif ( !checkdate((int) $dateExpl[1], (int) $dateExpl[0], (int) $dateExpl[2]) ) {
                        $endDateFormatError = true;
                  }
            }
            if ( $endDateFormatError ) {
                  $messageErrors[] = 17;
                  unset($endDate);
            }
            else {
                  $filters['endDate'] = strtotime("$endDate 23:59:59");
            }

            if ( $filters['endDate'] < $filters['startDate'] && !$endDateFormatError && !$startDateFormatError ) {
                  $filters['endDate'] = strtotime("$startDate 23:59:59");
                  $filters['startDate'] = strtotime("$endDate 00:00:00");
                  $tempVar = $endDate;
                  $endDate = $startDate;
                  $startDate = $tempVar;
            }
      }

      return $filters;
}

/*
 * Генериране на <option ... за select
 */

function generateOptionSelect($optionsArray = array(), $selectedOpt = '', $exclude = '-1', $filter_values = false) {
      foreach ( $optionsArray as $key => $value ) {
            if ( $filter_values ) {
                  $key = filter_var($key, FILTER_SANITIZE_STRING);
            }
            if ( $exclude == $key ) {
                  continue;
            }
            if ( $key == $selectedOpt ) {
                  $optionSelected = 'selected="selected"';
            }
            else {
                  $optionSelected = '';
            }

            $toReturn .= '<option value="' . $key . '" ' . $optionSelected . '>' . $value . '</option>' . "\n";
      }
      return $toReturn;
}

function printr($str) {
      echo '<pre>' . print_r($str, true) . '</pre>';
}